<?
/**************************************************************************************************
网站管理系统
Author			warmy
Version			1.0
Create Date		2006-10-24
**************************************************************************************************
获取权限类
**************************************************************************************************/
class warmy_right extends ANotify
{
	public $db;								//数据库连接
	public $right			= array();		//用户权限结合
	public $ugroup			= array();		//用户隶属组
	private $tablename		= RIGHTTABLE;		//权限表
	private $gtablename		= 'ugroup';		//用户组表
	//Construct
	//$inherit为true 获取当前用户的继承权限
	//$inherit为fase 获取当前拥护的继承权限和特殊权限
	function __construct($db,$username='',$type='U',$inherit = false,$tablename=RIGHTTABLE,$gtablename=GROUPTABLE)
	{
		$this->db		= $db;
		//权限表
		$this->tablename = $tablename;
		//用户组表
		$this->gtablename= $gtablename;
		//初始化用户权限
		//获取用户或用户组基本权限
		if(!$inherit)
			$this->get_right($username,$type);
		if($type == "U")
		{
			//获取用户隶属组
			$group = $this->get_group($username);
			$this->ugroup	= $group;
			//获取组相关权限
			for($i=0;$i<count($group);$i++)
				$this->get_right($group[$i],"G");
		}
		//移除数组中重复的组权限
		//array_unique($this->right);
	}
	function __destruct() 
	{
		if(isset($this->right))
			unset($this->right);
	}
	//获取指定用户权限
	function get_right($username,$type = 'U')
	{
		$sql = "select fun,micro from `{$this->tablename}` where name='$username' and `type`='$type'";
		if(($query = $this->db->query($sql)) == true)
		{
			while(($row = mysql_fetch_array($query,MYSQL_NUM)) == true)
			{
				//添加不重复功能点
				if(array_key_exists($row[0],$this->right))
					$this->right[$row[0]] = ($this->right[$row[0]]+0) | ($row[1]+0);
				else 
					$this->right[$row[0]] = $row[1];
			}
		}
	}
	
	//判断当前用户对所选择的功能是否具有对应的权限
	function checkright($fun,$micro = 0)
	{
		$bret	= false;
		if(array_key_exists($fun,$this->right))
		{
			if($micro>0)
			{
				if(($this->right[$fun] & $micro) == $micro)
					$bret	= true;
			}
			else 
				$bret	= true;
		}
		return $bret;
	}
	//获取当前用户所有组
	function get_group($username = '')
	{
		$group = array();
		$sql = "select `Group` from `{$this->gtablename}` where User = '$username'";
		if(($query = $this->db->query($sql))==true)
		{
			while(($row = mysql_fetch_array($query))==true)
				array_push($group,$row[0]);
		}
		return $group;
	}
	
	function get_WARMY_RIGHT()
	{
		return array("GROUPS"=>$this->ugroup,"RIGHTS"=>$this->right);
	}
}
?>